package com.netease.common;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Created by dongle on 2017/2/22.
 */
public class HttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
    private static HttpUtil instance = new HttpUtil();
    public static HttpUtil getInstance(){
        return instance;
    }

    public String commonGet(String urlStr, Map<String, String>headers) throws IOException {
        LOGGER.info("getUrl{} thread:{}", urlStr, Thread.currentThread().getId());

        URL url = new URL(urlStr);
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        System.out.println(urlStr);

        if (headers != null){
            for (Map.Entry<String, String> pair: headers.entrySet() ){
                connection.setRequestProperty(pair.getKey(), pair.getValue());
                System.out.println("headers:"+pair);
            }
        }
        connection.connect();
        connection.getInputStream();

        StringBuilder response = new StringBuilder();
        try (Scanner in = new Scanner(connection.getInputStream())) {
            while (in.hasNextLine()) {
//                System.out.println(in.nextLine());
                response.append(in.nextLine());
                response.append("\n");
            }
        }
        System.out.println(response.toString());
        return response.toString();
    }

    public String commonPost(String urlStr, Map<String, String>headers, String params) throws IOException {
        LOGGER.info("postrUrl{} thread:{}", urlStr, Thread.currentThread().getId());
        URL url = new URL(urlStr);
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        if (headers != null){
            for (Map.Entry<String, String> pair: headers.entrySet() ){
                connection.setRequestProperty(pair.getKey(), pair.getValue());
            }
        }

//        connection.setRequestProperty("Content-Type", "application/json");
//        connection.connect();
//        connection.getInputStream();

        try (PrintWriter out = new PrintWriter(connection.getOutputStream())){
            out.print(params);
        }

        StringBuilder response = new StringBuilder();
        try (Scanner in = new Scanner(connection.getInputStream())) {
            while (in.hasNextLine()) {
//                System.out.println(in.nextLine());
                response.append(in.nextLine());
                response.append("\n");
            }
        }
        System.out.println(response.toString());
        return response.toString();
    }

    public <T> String commonPut(String urlStr, Map<String, String>headers, T param) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String paramStr = mapper.writeValueAsString(param);
        return commonPut(urlStr, headers, paramStr);
    }
    public String commonPut(String urlStr, Map<String, String>headers, String params) throws IOException {
        LOGGER.info("putUrl{} thread:{}", urlStr, Thread.currentThread().getId());

        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json");

        if (headers != null){
            for (Map.Entry<String, String> pair: headers.entrySet() ){
                connection.setRequestProperty(pair.getKey(), pair.getValue());
            }
        }

//        connection.setRequestProperty("Content-Type", "application/json");
//        connection.connect();
//        connection.getInputStream();

        if (params != null) {
            try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
                out.print(params);
            }
            System.out.println("params:"+params);
        }

        StringBuilder response = new StringBuilder();
        try (Scanner in = new Scanner(connection.getInputStream())) {
            while (in.hasNextLine()) {
//                System.out.println(in.nextLine());
                response.append(in.nextLine());
                response.append("\n");
            }
        }
        System.out.println(response.toString());
        return response.toString();

    }
}
